<template>
  <div>
    <!-- 渲染角色列表 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="setRole">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 导入获取角色列表的方法
import { getRoles } from '@/api/setting'
// 导入获取用户详细信息方法
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'

export default {
  name: 'AssignRole',

  props: {
    roleId: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      roleIds: [], // 存放已选角色id
      roleList: [] // 角色列表
    }
  },

  created() {
    this.getRoles()
    this.getUserRoleId()
  },

  methods: {
    async getRoles() {
      // 获取所有角色
      const res = await getRoles()
      //   console.log(res)
      this.roleList = res.data.rows
    },

    // 获取已有角色
    async getUserRoleId() {
      const res = await getUserDetailById(this.roleId)
      this.roleIds = res.data.roleIds === null ? [] : res.data.roleIds
    },

    // 分配角色
    async setRole() {
      const res = await assignRoles({
        id: this.roleId,
        roleIds: this.roleIds
      })
      //   给用户提示
      this.$message.success(res.message)
      //   关闭弹框
      this.$emit('close')
    },
    cancleDialog() {
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
    margin-top: 30px;
}
</style>
